import {AsyncStorage} from "react-native";

let global = {
    AppRequestPath:"",
    AppRequestPath_spare:"",
    token:"",
    hotelId:"",
    WebSocketData:{"data":[],"random":1,"newrandom":0},
    AppType:"",
    Homepage:{orderBarIcon:"0",allOrderBarIcon:"0",contactsBarIcon:"0",mineBarIcon:"0",},           //Homepage页面红点
    CODE_PUSH_KEY:'9BENl9a9S--zEG3IqyHqvVG3Ikf9-NqXnn6oJx',
};
export default global

let ws=null;
export function getWs() {
    return this.ws;
}
export function creWebSocket(hotelId,userId){
    let REQUEST_URL = global.AppRequestPath+'/timer/creTimer';
    let parameters = new FormData();
    parameters.append("hotelId", hotelId);
    parameters.append("fu", "WHSKOrderGetInfo_Timer");
    parameters.append("websocketName", "globalWebsocket");
    parameters.append('jn', '{}');
    parameters.append('json', '{}');
    parameters.append('type', "proc");
    parameters.append('token', global.token);

    fetch(REQUEST_URL, {
        method: 'POST',
        body: parameters
    }).then((data) => {
        console.log(global.AppRequestPath+"/qmstimerWebSocket/"+hotelId+"/"+userId+"/globalWebsocket")
            this.ws = new WebSocket(global.AppRequestPath+"/qmstimerWebSocket/"+hotelId+"/"+userId+"/globalWebsocket")
            this.ws.onopen = () => {
                console.log("创建通道成功")
            }
            this.ws.onmessage = (event) => {
                // console.log(JSON.parse(event.data));
                // alert(event.data)
                // global.WebSocketData = JSON.parse(event.data)
                global.WebSocketData = {"data":JSON.parse(event.data),"random":Math.random()}
            }
            this.ws.onerror = (error) => {
                console.log(error)
                console.log("创建通道失败"+error.toString())
                // reconnect(hotelId,userId);
            }
            this.ws.onclose=()=>{
                console.log("通道销毁")
                // reconnect(hotelId,userId);
            }
        }
    ).catch((error) => {
        console.log(error.toString());
    })
}

// 重连
function reconnect(hotelId,userId) {
    setTimeout(function () {
        creWebSocket(hotelId,userId)
    }, 2000);
}

